package com.zg.ktcomwan.fragment

import android.os.Bundle
import android.text.Html
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.zg.ktcomwan.R
import com.zg.ktcomwan.base.BaseFragment
import com.zg.ktcomwan.base.log
import com.zg.ktcomwan.data.RetrofitUtils
import com.zg.ktcomwan.model.ProjectCategoryBean
import kotlinx.android.synthetic.main.common_tbar.*
import kotlinx.android.synthetic.main.fragment_project.*
import kotlinx.coroutines.launch

/***
 * @Author:      zxd
 * @CreateDate:  2021/7/6 15:34
 * @Description: 项目
 * 需要先请求接口，在赋值
 */
class ProjectFragment : BaseFragment() {

    private var categoryList = ArrayList<ProjectCategoryBean>()

    override fun getLayoutId(): Int {
        return R.layout.fragment_project
    }

    override fun afterCreate() {
        log("afterCreate")

        lifecycleScope.launch {
            categoryList =
                RetrofitUtils.service.getProjectCategory().data as ArrayList<ProjectCategoryBean>
            val mAdapter = ProjectAdapter(this@ProjectFragment, categoryList)
            projectVp.adapter = mAdapter
            TabLayoutMediator(projectTab, projectVp) { tab, position ->
                //tab.text = "OBJECT ${(position + 1)}"
                log("*******************${categoryList[position].name}")
                tab.text = Html.fromHtml(categoryList[position].name)
            }.attach()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // TODO: 2021/8/10 尝试请求接口。没发现是不是主线程
        log("start")
//        lifecycleScope.launch {
//            categoryList =
//                RetrofitUtils.service.getProjectCategory().data as ArrayList<ProjectCategoryBean>
//            log(categoryList.size)
//        }
        log("??????")
    }
}

class ProjectAdapter(
    fragment: Fragment,
    val categoryList: List<ProjectCategoryBean>
) : FragmentStateAdapter(fragment) {
    override fun getItemCount(): Int {
        return categoryList.size
    }

    override fun createFragment(position: Int): Fragment {
        /*val fragment = PerProjectFragment()
        fragment.arguments = Bundle().apply {
            putInt("id", categoryList[position].id)
        }
        return fragment*/
        return PerProjectFragment().newInstance(categoryList[position].id)
    }

}